package com.kevis.zhunblog.admin.handler;

import com.alibaba.fastjson.JSON;
import com.kevis.webCommon.web.exception.auth.CaptchaException;
import com.kevis.webCommon.web.domain.response.Result;
import com.kevis.webCommon.tools.web.ServletUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录认证失败处理器，直接实现这个接口，方便自己处理后续
 *
 * @Author kevis
 * @Date 2023/3/22 14:49
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        System.out.println("失败啦~~~"+e.getMessage());

        Result result = Result.failure(500, "登录失败");
        if (e instanceof CaptchaException) {
            result.setMsg("验证码有误");
        }
        //request.setAttribute("errorMsg","hello");
        //request.getRequestDispatcher("/hhm/login").forward(request, response);
        //request.getRequestDispatcher(this.forwardUrl).forward(request, response);
        //System.out.println("LoginFailureHandler:" + request);
        ServletUtil.write(JSON.toJSONString(result));
    }
}

/**
 * 另外一种方式，直接继承已经实现的转发类。这种方式可以跳转到登录页面，然后给登录页面传递一个值，弹窗提示失败
 */
//@Component
//public class LoginFailureHandler extends ForwardAuthenticationFailureHandler {
//    public LoginFailureHandler() {
//        super(UrlConstant.ADMIN_LOGIN_URL);
//    }
//
//    @Override
//    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
//        String errorMessage = exception.getMessage();
//        if(exception instanceof BadCredentialsException){
//            errorMessage = "登录失败";
//        }
//        request.setAttribute(ThymeleafConstant.ERROR_MESSAGE, errorMessage);
//        super.onAuthenticationFailure(request, response, exception);
//
//    }
//}
